import React, { useState } from 'react'
import { Form, Input, Button, Steps, message } from 'antd'
import { MailOutlined, LockOutlined, SafetyCertificateOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'

const { Step } = Steps

interface EmailForm {
  email: string
}

interface ResetForm {
  code: string
  password: string
  confirmPassword: string
}

const ForgotPasswordPage: React.FC = () => {
  const [current, setCurrent] = useState(0)
  const [loading, setLoading] = useState(false)
  const [email, setEmail] = useState('')
  const [countdown, setCountdown] = useState(0)
  const [form] = Form.useForm()
  const [resetForm] = Form.useForm()

  // Handle countdown timer
  React.useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000)
      return () => clearTimeout(timer)
    }
  }, [countdown])

  const onSendCode = async (values: EmailForm) => {
    setLoading(true)
    try {
      // TODO: Implement send verification code API
      console.log('Send code to:', values.email)
      message.success('验证码已发送到您的邮箱')
      setEmail(values.email)
      setCurrent(1)
      setCountdown(60) // Start 60 second countdown
    } catch (error) {
      message.error('发送验证码失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const onResetPassword = async (values: ResetForm) => {
    setLoading(true)
    try {
      // TODO: Implement reset password API
      console.log('Reset password with:', { email, ...values })
      message.success('密码重置成功！请使用新密码登录')
      setCurrent(2)
    } catch (error) {
      message.error('密码重置失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const onResendCode = async () => {
    if (countdown > 0) return
    
    setLoading(true)
    try {
      // TODO: Implement resend code API
      console.log('Resend code to:', email)
      message.success('验证码已重新发送')
      setCountdown(60)
    } catch (error) {
      message.error('发送失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const steps = [
    {
      title: '输入邮箱',
      icon: <MailOutlined />,
    },
    {
      title: '重置密码',
      icon: <LockOutlined />,
    },
    {
      title: '完成',
      icon: <SafetyCertificateOutlined />,
    },
  ]

  return (
    <>
      <h2 className="text-2xl font-bold text-center mb-6">忘记密码</h2>
      
      <Steps current={current} className="mb-8">
        {steps.map((item, index) => (
          <Step key={index} title={item.title} icon={item.icon} />
        ))}
      </Steps>

      {current === 0 && (
        <Form
          form={form}
          name="forgot-password"
          onFinish={onSendCode}
          size="large"
        >
          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱！' },
              { type: 'email', message: '请输入有效的邮箱地址！' }
            ]}
          >
            <Input
              prefix={<MailOutlined />}
              placeholder="请输入注册时的邮箱"
              autoComplete="email"
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              className="w-full"
            >
              发送验证码
            </Button>
          </Form.Item>

          <div className="text-center">
            <Link to="/auth/login">返回登录</Link>
          </div>
        </Form>
      )}

      {current === 1 && (
        <Form
          form={resetForm}
          name="reset-password"
          onFinish={onResetPassword}
          size="large"
        >
          <div className="mb-4 text-center text-gray-600">
            验证码已发送至：{email}
          </div>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入验证码！' },
              { len: 6, message: '验证码为6位数字！' }
            ]}
          >
            <Input
              prefix={<SafetyCertificateOutlined />}
              placeholder="请输入6位验证码"
              maxLength={6}
              addonAfter={
                <Button
                  size="small"
                  type="link"
                  onClick={onResendCode}
                  disabled={countdown > 0}
                  loading={loading && countdown === 0}
                >
                  {countdown > 0 ? `${countdown}秒后重发` : '重新发送'}
                </Button>
              }
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入新密码！' },
              { min: 8, message: '密码至少8个字符！' },
              {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d)/,
                message: '密码必须包含字母和数字！'
              }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入新密码"
              autoComplete="new-password"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认新密码！' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不一致！'))
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="确认新密码"
              autoComplete="new-password"
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              className="w-full"
            >
              重置密码
            </Button>
          </Form.Item>

          <div className="text-center">
            <Link to="/auth/login">返回登录</Link>
          </div>
        </Form>
      )}

      {current === 2 && (
        <div className="text-center">
          <div className="mb-4">
            <SafetyCertificateOutlined style={{ fontSize: 48, color: '#52c41a' }} />
          </div>
          <h3 className="text-xl mb-4">密码重置成功！</h3>
          <p className="text-gray-600 mb-6">您的密码已成功重置，请使用新密码登录。</p>
          <Link to="/auth/login">
            <Button type="primary" size="large">
              立即登录
            </Button>
          </Link>
        </div>
      )}
    </>
  )
}

export default ForgotPasswordPage